<script setup lang="tsx">
import { computed, defineOptions, reactive, ref } from "vue";
import { SimpleScrollbar } from "@sa//materials";
import { $t } from "@/locales";
import { useForm } from "@/hooks/common/form";
import type { ApiSysCgConfigOut, CgConfig } from "@/api-services";
import { SyscgconfigApi } from "@/api-services";
import { queryDone } from "@/utils/api";
import { feature, getAPI } from "@/axios-utils";
import { NetoKit } from "@/typings/neto";

defineOptions({
  name: "SysCgConfigInfo",
});

const operateType = ref<OperateType>("add");

export type OperateType = UI.TableOperateType;
type CheckedType = boolean | string | number;
const visible = ref<boolean>(false);
const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t("page.manage.menu.addMenu"),
    // addChild: $t("page.manage.menu.addChildMenu"),
    edit: $t("page.manage.menu.editMenu"),
  };
  return titles[operateType.value];
});
const { formRef, validate, restoreValidation } = useForm();
//通过 Omit 移除原类型中的 config 属性，再通过交叉类型重新定义必选的 config 属性：
type ConfigModel = Omit<ApiSysCgConfigOut, "config"> & {
  //通过IsNonNullable将属性全都转换为非null
  config: NetoKit.IsNonNullable<CgConfig>; // 强制必选且类型为 CgConfig
};
const initModel = () => {
  const result: ConfigModel = {
    config: {
      dbType: 0, // 初始化 dbType
      entityUseEfAttribute: false, // 默认值
      entityUseSqlSugarAttribute: false, // 默认值
      projectName: "",
      dbConn: "",
      saveDirectory: "",
      dbTableReplace: "",
      dbTableNoPrefix: "",
      entityReplace: "",
      entityPrefix: "",
      mvcApplicationNameSpace: "",

      mvcControllerNameSpace: "",
      mvcControllerBase: "",
      mvcArea: "",
      mvcPrefix: "",
      apiArea: "",
      apiPrefix: "",
      apiNameSpace: "",
    },
    id: 0,
  };

  return result;
};
let model = reactive<ConfigModel>(initModel());

// const templetTypeOptions = computed(() => {
//   return Object.entries(CgConfigTempletType)
//     .filter(([key]) => Number.isNaN(Number(key)))
//     .map(([key, value]) => ({ label: key, value }));
// });

const templetTypeOptions = computed(() => {
  const templetTypes = {
    默认模板: 0,
    自定义模板: 1,
  };
  return Object.entries(templetTypes).map(([key, value]) => ({
    label: key,
    value,
  }));
});

const dbTypeOptions = computed(() => {
  const dbTypes = {
    MySql: 0,
    SqlServer: 1,
    Sqlite: 2,
    Oracle: 3,
    PostgreSQL: 4,
    Dm: 5,
    Kdbndp: 6,
    Oscar: 7,
    MySqlConnector: 8,
    Access: 9,
    OpenGauss: 10,
    QuestDB: 11,
    HG: 12,
    ClickHouse: 13,
    GBase: 14,
    Odbc: 15,
    OceanBaseForOracle: 16,
    TDengine: 17,
    GaussDB: 18,
    OceanBase: 19,
    Tidb: 20,
    Vastbase: 21,
    PolarDB: 22,
    Doris: 23,
    Xugu: 24,
    GoldenDB: 25,
    TDSQLForPGODBC: 26,
    TDSQL: 27,
    HANA: 28,
    DB2: 29,
    GaussDBNative: 30,
    Custom: 900,
  };

  return Object.entries(dbTypes).map(([key, value]) => ({ label: key, value }));
});
const handleEntityUseEfAttributeChange = (checked: CheckedType) => {
  if (process.env.NODE_ENV === "development")
    console.log("Entity Use EF Attribute changed to:", checked);
  // 在这里添加你需要执行的逻辑
};

const handleEntityUseSqlSugarAttributeChange = (checked: CheckedType) => {
  if (process.env.NODE_ENV === "development")
    console.log("Entity Use SqlSugar Attribute changed to:", checked);
  // 在这里添加你需要执行的逻辑
};

function closeModalInfo() {
  visible.value = false;
}

interface Emits {
  (e: "submitted"): void;
}

const emit = defineEmits<Emits>();
async function handleSubmit() {
  await validate();

  if (operateType.value === "add") {
    const [err, res] = await feature(getAPI(SyscgconfigApi).insert(model));
    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t("common.addSuccess"));
        closeModalInfo();
        emit("submitted");
      }
    });
  } else if (operateType.value === "edit") {
    // 提交请求
    const [err, res] = await feature(getAPI(SyscgconfigApi).update(model));
    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t("common.updateSuccess"));
        closeModalInfo();
        emit("submitted");
      }
    });
  }
}
const handleInit = async (id?: number | undefined, ot?: OperateType) => {
  if (ot) {
    operateType.value = ot;
  }
  visible.value = true;
  if (process.env.NODE_ENV === "development")
    console.log(`handleInit-${operateType.value}-${id}`);
  if (operateType.value === "add") {
    // 初始化新增操作的数据
    model = initModel();
  } else if (operateType.value === "edit" && id !== undefined) {
    if (process.env.NODE_ENV === "development") console.log(`edit-${id}`);
    // 获取编辑数据
    const [err, res] = await feature(getAPI(SyscgconfigApi).get(id as number));

    queryDone(err, async () => {
      if (res?.data.data) {
        Object.assign(model, res.data.data); // 更新模型数据
        if (process.env.NODE_ENV === "development") console.log(model);
      } else {
        window.$message?.error($t("common.fetchFailed"));
      }
    });
  }
};

defineExpose({
  handleInit,
});
</script>

<template>
  <NModal v-model:open="visible" :title="title" width="1000px" :show-full-screen="true">
    <SimpleScrollbar>
      <ElForm ref="formRef" :model="model" label-width="auto">
        <ElRow :gutter="16">
          <ElCol :lg="12" :xs="24">
            <ElFormItem label="配置名称" name="name">
              <ElInput v-model="model.name!" />
            </ElFormItem>
          </ElCol>
          <ElCol :lg="12" :xs="24">
            <ElFormItem label="模板类型" name="templetType">
              <ElSelect v-model="model.templetType" :options="templetTypeOptions" />
            </ElFormItem>
          </ElCol>
        </ElRow>
        <ElCollapse :lg="24" :xs="24" :active-key="['0', '1', '2', '3', '4', '5']">
          <!-- <ElCollapseItem key="0" title="基本信息"> </ElCollapseItem> -->
          <ElCollapseItem key="1" title="配置信息">
            <ElRow :gutter="16">
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="项目名称" name="config.projectName">
                  <ElInput v-model="model.config.projectName" />
                </ElFormItem>
              </ElCol>
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="数据库-连接字符串" name="config.dbConn">
                  <ElInput type="textarea" v-model="model.config.dbConn" :rows="4" />
                </ElFormItem>
              </ElCol>
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="数据库类型" name="dbType">
                  <ElSelect v-model="model.config.dbType" :options="dbTypeOptions" />
                </ElFormItem>
              </ElCol>
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="保存目录" name="config.saveDirectory" extra="例如：api或api\test或api\neto">
                  <ElInput v-model="model.config.saveDirectory" />
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElCollapseItem>
          <ElCollapseItem key="2" title="DB">
            <ElRow :gutter="16">
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="DB-表名字符串替换" name="config.dbTableReplace" extra=" 例如：Sys_=Sys,Sys=Sys">
                  <ElInput v-model="model.config.dbTableReplace" />
                </ElFormItem>
              </ElCol>
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="DB-表名去前缀" name="config.dbTableNoPrefix" extra=" 例如：Sys_,Sys,直接把已制定名称开头的前缀去掉">
                  <ElInput v-model="model.config.dbTableNoPrefix" />
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElCollapseItem>
          <ElCollapseItem key="3" title="实体">
            <ElRow :gutter="16">
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="实体使用EF特性" name="config.entityUseEfAttribute">
                  <ElSwitch v-model:model-value="model.config.entityUseEfAttribute"
                    @change="handleEntityUseEfAttributeChange" />
                </ElFormItem>
              </ElCol>
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="实体使用SqlSugar特性" name="config.entityUseSqlSugarAttribute">
                  <ElSwitch v-model:model-value="model.config.entityUseSqlSugarAttribute"
                    @change="handleEntityUseSqlSugarAttributeChange" />
                </ElFormItem>
              </ElCol>
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="实体-替换" name="config.entityReplace" extra="例如：Sys_=Ht,Sys=Ht或者Sys_=Ht,Sys=Ht">
                  <ElInput v-model="model.config.entityReplace" />
                </ElFormItem>
              </ElCol>
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="实体-前缀" name="config.entityPrefix" extra="例如：在表User前面加上前缀Ht 变成 HtUser">
                  <ElInput v-model="model.config.entityPrefix" />
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElCollapseItem>

          <ElCollapseItem key="5" title="API">
            <ElRow :gutter="16">
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="API 区域" name="config.apiArea">
                  <ElInput v-model="model.config.apiArea" />
                </ElFormItem>
              </ElCol>
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="Api-前缀" name="config.apiPrefix" extra="例如：服务，Dto，input，out的前缀，用于区分多个Area防止重复">
                  <ElInput v-model="model.config.apiPrefix" />
                </ElFormItem>
              </ElCol>
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="API应用层-命名空间" name="config.apiNameSpace"
                  extra="API不用此命名空间，默认命名按：项目名称.Application.Api前缀">
                  <ElInput v-model="model.config.apiNameSpace" />
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElCollapseItem>

          <ElCollapseItem key="4" title="MVC">
            <ElRow :gutter="16">
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="MVC-区域" name="config.mvcArea">
                  <ElInput v-model="model.config.mvcArea" />
                </ElFormItem>
              </ElCol>
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="MVC-前缀" name="config.mvcPrefix" extra="例如：在表User前面加上前缀Ht 变成 HtUser">
                  <ElInput v-model="model.config.mvcPrefix" />
                </ElFormItem>
              </ElCol>
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="MVC控制器-命名空间" name="config.mvcControllerNameSpace"
                  extra="默认规则：项目名称.Web.Entry.Areas.Mvc区域.Controllers , 默认命名空间：Neto.Web.Entry.Areas.HtAdmin.Controllers">
                  <ElInput v-model="model.config.mvcControllerNameSpace" />
                </ElFormItem>
              </ElCol>
              <ElCol :lg="12" :xs="24">
                <ElFormItem label="MVC应用层-命名空间" name="config.mvcApplicationNameSpace"
                  extra="默认规则：项目名称.Application.Mvc区域 , 默认命名空间：Neto.Application.HtAdmin">
                  <ElInput v-model="model.config.mvcApplicationNameSpace" />
                </ElFormItem>
              </ElCol>

              <ElCol :lg="12" :xs="24">
                <ElFormItem label="MVC控制器-继承的基础类" name="config.mvcControllerBase" extra="MVC控制器继承的基础 Controller">
                  <ElInput v-model="model.config.mvcControllerBase" />
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElCollapseItem>
        </ElCollapse>
      </ElForm>
    </SimpleScrollbar>
    <template #footer>
      <ElSpace :size="16">
        <ElButton @click="closeModalInfo">{{ $t("common.cancel") }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{
          $t("common.confirm")
        }}</ElButton>
      </ElSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
